<?php

namespace App\Admin\Actions\Grid\Withdraw;

use App\Models\UserWithdraw;
use App\Services\Base\CacheService;
use App\Services\BlockChainApiServices;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;

class RefreshWithdrawBalanceGrid extends RowAction
{
    /**
     * @return string
     */
    protected $title = '刷新余额';

    protected function html()
    {
        $money = asMoney($this->row->{$this->getColumnName()});
        return <<<HTML
 <div style="text-align: center">
 <div >{$money}</div>
<button class="{$this->getElementClass()} btn btn-primary btn-sm btn-outline">刷新</button>
</div>
HTML;
    }

    public function handle(Request $request)
    {
        try {
            $class = $request->class;
            $column = $request->column;
            $id = $this->getKey();
            $model = $class::find($id);

            $chain = "TRON";
            $address = "address";
            if (!$model->{$address}) {
                return $this->response()->error("请设置钱包地址");
            }

            $chain_service = new BlockChainApiServices($chain);
            if ($column == "system_value") {
                $balance = $chain_service->balance($model->{$address}, $chain_service->getSystemWei($chain));
            } else {
                $balance = $chain_service->balanceToken($model->{$address}, $chain_service->getContract($chain), $chain_service->getWei($chain));
            }

            $model->{$column} = $balance;
            $model->save();

            CacheService::del("balance_not_sufficient");

            return $this->response()->success("success")->refresh();
        } catch (\Exception $e) {
            return $this->response()->error($e->getMessage());
        }
    }


    public function parameters()
    {
        return [
            'class' => $this->modelClass(),
            'column' => $this->getColumnName(),
        ];
    }

    public function getColumnName()
    {
        return $this->column->getName();
    }

    public function modelClass()
    {
        return get_class($this->parent->model()->repository()->model());
    }
}
